<template>
  <div class="map-container" id="container"></div>
</template>

<script>
import LabelCluster from './overlay'
import ClusterBubble from './ClusterBubble'
import { getAction } from '@/api/manage'
import Viewer from 'viewerjs'
import 'viewerjs/dist/viewer.css'
import { findEnableDictItemsbyCode } from '@/api/api'
export default {
  name: '',
  props: ['informationId'],
  watch: {
    informationId(val) {
      this.clearOverlay()
      this.queryParams.industryIds = val
      this.getCurrentPoliceAgencyInfo(1)
    },
    async type(val) {
      // * 用于监听type==5时 查询辖区列表绘制 同时开启父组件的对应功能显示隐藏
      if (val == 5) {
        this.filteredPoliceJurisdictionList = await this.getFilteredPoliceJurisdictionList(this.queryParams.id)
        this.drawPolygon(this.filteredPoliceJurisdictionList)
        this.$emit('isShowPolyon', true)
        this.$emit('hiddenPolyonButton', false)
      } else {
        this.$emit('hiddenPolyonButton', true)
      }
    },
  },
  data() {
    return {
      map: {},
      MarkList: [],
      queryParams: {
        id: '',
        industryIds: '',
      },
      overlayList: [],
      type: 0,
      imgPrefix: '',
      parentId: '',
      loading: false,
      layerType: 0,
    }
  },
  mounted() {
    this.firstInit()
  },
  methods: {
    firstInit() {
      console.log('hhhhh-hhhh')
      this.queryParams.id = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value.policeAgencyId
      this.queryParams.type = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value.policeAgencyType
      this.init()
      this.getCurrentPoliceAgencyInfo()
      this.getDist()
    },

    // 获取当前警务机构信息
    async getCurrentPoliceAgencyInfo(flag) {
      console.log('hihihihihihi')
      if (this.loading == true) {
        this.$message.warning('正在加载,请稍后')
      }

      this.loading = true

      let data = {}
      if (flag != undefined && flag == -1) {
        // 如果行政区上浮时 传action = -1
        data = { id: this.queryParams.id, action: -1, type: this.queryParams.type - 1 }
      } else if (flag != undefined && flag == 1) {
        // 行业选择 id 传 父id
        data = { id: this.parentId, type: this.queryParams.type - 1, industryIds: this.queryParams.industryIds }
      } else {
        data = { ...this.queryParams }
      }

      this.$emit('changeLayer', this.queryParams.id, this.layerType)

      let { result } = await getAction('/sys/statistics/map', data)
      this.loading = false
      this.overlayList = result
      if (result.length !== 0) {
        this.clearOverlay()
        this.type = result[0].type
        this.queryParams.type = result[0].type
        this.map.setZoom(this.getZoom(result[0].type))
        this.parentId = result[0].parentId
        if (this.type == 5) {
          let geometries = result.map((item) => {
            return {
              id: item.id,
              type: item.type,
              content: item.name,
              parentId: item.parentId,
              selfCount: item.selfCount,
              position: new TMap.LatLng(item.lat, item.lng),
            }
          })
          this.markerCluster(geometries)
          return
        }
        this.drawOverlay()
      }
    },

    // 用于父组件jump_target_position_at_map 方法
    async jump_position_at_map(params) {
      let { policeAgencyType } = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
      console.log(policeAgencyType)
      this.queryParams.type = 4
      this.queryParams.id = params.parentId

      await this.getCurrentPoliceAgencyInfo()
      this.layerType = 4 - policeAgencyType
      this.$emit('changeLayer', this.queryParams.id, this.layerType)
      this.map.setCenter(new TMap.LatLng(params.lat, params.lng))
      this.map.setZoom(20)
    },

    // 获取当前警务机构信息 用于父组件路由切换
    async initPoliceAgencyInfo(flag) {
      console.log('888888')
      let { policeAgencyId: id, policeAgencyType: type } = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value

      this.$emit('changeLayer', id, 0)

      let { result } = await getAction('/sys/statistics/map', { id, type })
      this.overlayList = result
      if (result.length !== 0) {
        this.clearOverlay()
        if (this.infoWindow) this.infoWindow.close()
        this.clearPolygon()
        this.type = result[0].type
        this.queryParams.type = result[0].type
        this.map.setZoom(this.getZoom(result[0].type))
        this.parentId = result[0].parentId
        this.drawOverlay()
      }
    },

    async getDist() {
      let res = await findEnableDictItemsbyCode({ code: 'static_server' })
      this.imgPrefix = res.result[0].value
    },

    // * 行政区上浮
    handelBackMapLayer() {
      this.layerType -= 1
      this.queryParams.id = this.parentId
      if (this.infoWindow) this.infoWindow.close() //初始关闭信息窗关闭
      this.getCurrentPoliceAgencyInfo(-1)
      this.clearPolygon()
    },

    init() {
      let { policeAgencyLat, policeAgencyLng } = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
      this.map = new TMap.Map(document.getElementById('container'), {
        center: new TMap.LatLng(policeAgencyLat, policeAgencyLng), // 西安
        // center: new TMap.LatLng(32.832803, 109.368639), // 浔阳
        // center: new TMap.LatLng(40.040452, 116.273486), // 北京
        zoom: 14,
        minZoom: 6,
        maxZoom: 20,
        // viewMode: '2D',
        // pitch: 45,
        doubleClickZoom: false,
        showControl: false,
        mapStyleId: 'style1',
        baseMap: [
          { type: 'vector' }, //设置矢量底图
          {
            type: 'building3d',
            features: ['base'], //路况图类型，目前支持路况线网
            opacity: 0.3, //路况线网图的透明度
          },
        ],
      })
    },

    // 自定义聚合
    markerCluster(geometries) {
      let _this = this
      var markerCluster = new TMap.MarkerCluster({
        map: this.map,
        enableDefaultStyle: false, // 启用默认样式
        minimumClusterSize: 3, // 形成聚合簇的最小个数
        geometries,
        zoomOnClick: true, // 点击簇时放大至簇内点分离
        gridSize: 60, // 聚合算法的可聚合距离
        averageCenter: false, // 每个聚和簇的中心是否应该是聚类中所有标记的平均值
        maxZoom: 22, // 采用聚合策略的最大缩放级别
      })

      var clusterBubbleList = []

      // 监听聚合簇变化
      markerCluster.on('cluster_changed', (e) => {
        if (_this.type !== 5) {
          if (clusterBubbleList.length) {
            clusterBubbleList.forEach(function (item) {
              item.destroy()
            })
            clusterBubbleList = []
          }
          return
        }

        this.clearOverlay()
        // 销毁旧聚合簇生成的覆盖物
        if (clusterBubbleList.length) {
          clusterBubbleList.forEach(function (item) {
            item.destroy()
          })
          clusterBubbleList = []
        }

        // 根据新的聚合簇数组生成新的覆盖物和点标记图层
        var clusters = markerCluster.getClusters()

        clusters.forEach((item) => {
          if (item.geometries.length > 1) {
            let clusterBubble = new ClusterBubble({
              map: this.map,
              position: item.center,
              content: item.geometries.length,
            })
            clusterBubble.on('click', () => {
              this.map.fitBounds(item.bounds)
            })
            clusterBubbleList.push(clusterBubble)
          } else {
            item.geometries.forEach((item) => {
              const label = new LabelCluster({
                map: this.map,
                ...item,
              })
              this.MarkList.push(label)

              label.on('click', function (e, id, type, position, parentId) {
                if (_this.infoWindow) _this.infoWindow.close() //初始关闭信息窗关闭
                _this.getCompanyInfo(id, position, parentId)
              })
            })
          }
        })
      })
    },

    addGeoLisener() {
      //通过off方法解绑点击事件
      //Map实例创建后，通过on方法绑定点击事件

      this.map.on('dragend', () => {
        this.onMoveEnd()
      })

      // this.map.on('zoomstart', () => {
      //   console.log('zoomstart')
      // })

      this.map.on('zoomend', () => {
        // console.log('zoomend')
        // console.log(this.map.getZoom(), 'zoomend')
      })

      this.map.on('zoom', () => {
        this.onZoomEnd()
      })
    },

    // dragend
    onMoveEnd() {},

    // zoom
    onZoomEnd() {},

    logMapBounds() {
      // 获取当前地图边界经纬度
      let bounds = this.map.getBounds()
      console.log(bounds._sw, bounds._ne)
      return [
        { lng: bounds._sw.lng, lat: bounds._sw.lat },
        { lng: bounds._ne.lng, lat: bounds._ne.lat },
      ]
    },

    // 地图缩放值与层级互相转化
    getZoom(type) {
      let zoom
      if (type === 2) {
        zoom = 8
      } else if (type === 3) {
        zoom = 10
      } else if (type === 4) {
        zoom = 11
      } else if (type === 5) {
        zoom = 14
      }
      return zoom
    },

    computedOrgType() {
      // ! 1.省 6  2.市 8  3.区 11 4.派出所 14 5 企业
      let orgType
      if (zoom >= 6 && zoom < 8) {
        orgType = 1
      } else if (zoom >= 8 && zoom < 11) {
        orgType = 2
      } else if (zoom >= 11 && zoom <= 14) {
        orgType = 3
      } else if (zoom >= 14) {
        orgType = 4
      }
      return orgType
    },

    drawOverlay() {
      // * length lng lat
      let _this = this
      this.overlayList.forEach((item) => {
        const center = new TMap.LatLng(item.lat, item.lng) // 设置中心点坐标

        let targetMarker = {
          id: item.id,
          type: item.type,
          parentId: item.parentId,
          selfCount: item.selfCount,
          position: center, // 设置信息框位置
          content: item.name, // 设置信息框内容
        }

        const label = new LabelCluster({
          map: this.map,
          ...targetMarker,
        })
        this.MarkList.push(label)

        //pc端使用click事件
        label.on('click', function (e, id, type, position, parentId) {
          if (type !== 5) {
            _this.layerType += 1
            _this.map.setCenter(new TMap.LatLng(position.lat, position.lng))
            _this.queryParams.id = id
            _this.getCurrentPoliceAgencyInfo()
          } else {
            if (_this.infoWindow) _this.infoWindow.close() //初始关闭信息窗关闭
            _this.getCompanyInfo(id, position, parentId)
          }
        })
      })
    },

    clearOverlay() {
      if (this.MarkList) {
        this.MarkList.forEach((mark) => {
          mark.setMap(null)
        })
      }
    },

    drawPolygon(list) {
      let styleObj = {}
      let geometriesList = []

      let lableStyleObj = {}
      let lableGeometriesList = []
      list.forEach((item) => {
        let color = item.positionColour.replace(')', ',.5)')
        let bColor = item.positionColour
        // polygon
        styleObj['polygon' + item.id] = new TMap.PolygonStyle({
          color: color, // 面填充色
          showBorder: true, // 是否显示拔起面的边线
          // extrudeHeight: 3000, //多边形拔起高度
          borderColor: bColor, //边线颜色
        })

        let path = []
        item.areaPosition.split(';').forEach((iterator) => {
          const [lng, lat] = iterator.split(',') // 缓存分割结果
          path.push(new TMap.LatLng(lat, lng))
        })
        geometriesList.push({
          id: 'polygon' + item.id, // 多边形图形数据的标志信息
          styleId: 'polygon' + item.id, // 样式id
          paths: path, // 多边形的位置信息
        })

        // lable
        lableStyleObj['label' + item.id] = new TMap.LabelStyle({
          color: '#3777FF', //颜色属性
          size: 20, //文字大小属性
          offset: { x: 0, y: 0 }, //文字偏移属性单位为像素
          angle: 0, //文字旋转属性
          alignment: 'center', //文字水平对齐属性
          verticalAlignment: 'middle', //文字垂直对齐属性
        })

        lableGeometriesList.push({
          id: 'label' + item.id, // 点图形数据的标志信息
          styleId: 'label' + item.id, // 样式id
          position: new TMap.LatLng(item.lat, item.lng), //标注点位置
          content: item.jurisdictionName, //标注文本
          properties: {
            //标注点的属性数据
            title: 'label',
          },
        })
      })

      // 初始化polygon
      this.polygon = new TMap.MultiPolygon({
        // id: 'polygon-layer', // 图层id
        map: this.map, // 显示多边形图层的底图
        styles: styleObj,
        geometries: geometriesList,
      })

      this.label = new TMap.MultiLabel({
        // id: 'label-layer',
        map: this.map,
        styles: lableStyleObj,
        geometries: lableGeometriesList,
      })
    },

    clearPolygon() {
      if (this.polygon && this.polygon.getGeometries().length > 0)
        this.polygon.getGeometries().forEach((item) => this.polygon.remove(item.id))
      if (this.label && this.label.getGeometries().length > 0)
        this.label.getGeometries().forEach((item) => this.label.remove(item.id))
    },

    parentComponentDrawPolygon() {
      this.drawPolygon(this.filteredPoliceJurisdictionList)
    },

    // * 获取辖区列表
    async getFilteredPoliceJurisdictionList(policeAgencyId) {
      const { result: policeJurisdictionList } = await getAction(
        '/police/jurisdiction/find_police_agency_jurisdiction_list',
        {
          policeAgencyId,
          pigeSize: 99999,
        }
      )
      const filteredPoliceJurisdictionList = policeJurisdictionList.filter((item) => !!item.areaPosition)
      return filteredPoliceJurisdictionList
    },

    // * 获取公司详情
    async getCompanyInfo(id, position, parentId) {
      let { result } = await getAction('/company/message/record', { id })
      // console.log(result)
      let certificateUrlG, businessLicenseUrlG
      if (result.companyInfo.certificateStatus == 1) {
        let { certificateUrl } = await this.getLicenseByCompanyId(id)
        certificateUrlG = certificateUrl
      }

      if (result.companyInfo.businessStatus == 1) {
        let { businessLicenseUrl } = await this.getbusinessDetail(id)
        businessLicenseUrlG = businessLicenseUrl
      }

      let checkTask = await this.getCheckTask(id, parentId)

      let ret = await this.getCompanyImg(id)
      this.openWindow(result, certificateUrlG, businessLicenseUrlG, checkTask, ret)
      this.infoWindow.open()
      this.infoWindow.setPosition(new TMap.LatLng(position.lat, position.lng))
      // _this.infoWindow.setContent(id.toString()) //设置信息窗内容
    },

    // 获取企业许可证详情
    async getLicenseByCompanyId(id) {
      let { result } = await getAction('/company/certificate/detail', { companyId: id })
      return result
    },

    async getbusinessDetail(id) {
      let { result } = await getAction('/company/message/business_detail', { companyId: id })
      return result
    },

    async getCompanyImg(id) {
      let { result } = await getAction('/sys/images_path/list', { bizId: id, bizType: 4 })
      return result
    },

    // 获取最后一次检查详情
    async getCheckTask(id, parentId) {
      let {
        result: { records },
      } = await getAction('/police/check_task/page', { companyMessageId: id, policeAgencyId: parentId, checkStatus: 3 })
      return records
    },

    async openWindow(params, certificateUrl, businessLicenseUrl, checkTask, companyImgPath) {
      let close = require('@/assets/imgs/dashboard/close.png')
      let position = require('@/assets/imgs/dashboard/position.png')

      const companyImg =
        companyImgPath.length > 0
          ? `${this.imgPrefix}${companyImgPath[0].path}`
          : require('@/assets/imgs/dashboard/shangpu.png')

      const { userImage } = params.policeUserInfo
      const policeImg = userImage
        ? `${this.imgPrefix}${userImage}`
        : require('@/assets/imgs/dashboard/police_noPhoto.png')

      let a, b, c, d, e, f
      // console.log(checkTask, 'checkTaskcheckTaskcheckTask')
      // * params.companyInfo.businessStatus == 1 // 营业执照 0否 1 是
      // * params.companyInfo.certificateStatus == 1 // 是否完善特行许可证信息 0.否 1.是

      if (params.companyInfo.businessStatus == 1) {
        let url = this.imgPrefix + businessLicenseUrl
        a = `<div class="value click-style" onclick=showImg('minImg${businessLicenseUrl}')>查看证书
            <img
              id="minImg${businessLicenseUrl}"
              src="${url}"
              data-original="${url}"sz
              />
            </div>`
      } else {
        a = `<div class="value">未上传</div>`
      }

      if (params.companyInfo.certificateStatus == 1) {
        let url = this.imgPrefix + certificateUrl
        b = `<div class="value click-style" onclick=showImg('minImg${certificateUrl}')>查看证书
            <img
              id="minImg${certificateUrl}"
              src="${url}"
              data-original="${url}"
              />
            </div>`
      } else {
        b = `<div class="value">未上传</div>`
      }

      if (checkTask.length > 0) {
        c = `<div class="value">${checkTask[0].checkTime}</div>`
        d = `<div class="value">${checkTask[0].industryExamineName}</div>`
        e = `<div class="value">${checkTask[0].checkResult_dictText}</div>`

        var checkTaskObj = JSON.stringify(checkTask[0]).replace(/"/g, `'`)
        f = `
        <div class="f1 flex">
          <div class="lable">检查详情:</div>
            <div class="value click-style" onclick="jumpGooverDetail(${checkTaskObj})">查看</div>
          </div>
        <div class="f1 flex click-style justify-end" style="padding-right:5px" onclick="jumpGoover(${checkTaskObj})">全部检查记录></div>
        `

        // f = `<div class="value click-style" onclick="jumpGoover(${checkTaskObj})">全部检查记录></div>`
      } else {
        c = d = e = `<div class="value">暂无</div>`
        f = `<div class="value">暂无</div>`
      }

      let pre = `
      <div class="info-window flex column">
       <div class="info-window-title flex">
         <img class="close" onclick="close_x()" src="${close}" alt="" />
         <img class="companyImg" src="${companyImg}" alt=""  id="minImg${companyImg}" data-original="${companyImg}" onclick=showImg('minImg${companyImg}') />
        <div class="right-content flex column justify-around">
          <div class="companyName flex align-center">
            <div class="company text-overflow" style="max-width:220px">${params.companyInfo.companyName}</div>
            <div class="industry">${params.informationInfo.informationName}</div>
          </div>
          <div class="address flex align-center">
            <img src="${position}" alt="" />
            <span class="text-overflow" style="max-width:280px">${params.companyInfo.addressDetail}</span>
          </div>
        </div>
      </div>
      <div class="info-content">
        <span class="common-title">安全负责人信息</span>
        <div class="common-info-wrap flex">
          <div class="f1 flex">
            <div class="lable">姓 名:</div>
            <div class="value">${params.dutyPersonInfo.dutyPersonName || '暂无'}</div>
          </div>
          <div class="f1 flex">
            <div class="lable">联系方式:</div>
            <div class="value">${params.dutyPersonInfo.mobile || '暂无'}</div>
          </div>
        </div>
        <div class="common-info-wrap flex">
          <div class="lable">身份证号:</div>
          <div class="value">${params.dutyPersonInfo.idCard || '暂无'}</div>
        </div>
        <div class="common-info-wrap flex" style="margin-bottom: 0">
          <div class="lable">户籍地址:</div>
          <div class="value">${params.dutyPersonInfo.residenceDetail || '暂无'}</div>
        </div>
        <span class="common-title">资质信息</span>
        <div class="common-info-wrap flex" style="margin-bottom: 0">
          <div class="f1 flex" v-if="false">
            <div class="lable">营业执照:</div>
      `

      let mid = `
       </div>
          <div class="f1 flex">
            <div class="lable">特行证书:</div>`

      let suf =
        `
      </div>
        </div>
        <span class="common-title">责任民警</span>
        <div class="common-info-wrap flex">
          <div class="lable" style="width: 80px">所属派出所:</div>
          <div class="value">${params.policeAgencyInfo.policeAgencyName}</div>
        </div>
        <div class="common-info-wrap flex">
          <div class="lable">民警姓名:</div>
          <div class="value">${params.policeUserInfo.userName}</div>
        </div>
        <div class="common-info-wrap flex" style="margin-bottom: 0">
          <div class="lable">联系方式:</div>
          <div class="value">${params.policeUserInfo.mobile}</div>
        </div>

        <img class="police-img" src="${policeImg}" alt=""  id="minImg${policeImg}" data-original="${policeImg}" onclick=showImg('minImg${policeImg}') />

        <span class="common-title">最新检查记录</span>
        <div class="common-info-wrap flex">
          <div class="lable">检查时间:</div>` +
        c +
        `</div>
        <div class="common-info-wrap flex">
          <div class="lable">检查类型:</div>` +
        d +
        `</div>
        <div class="common-info-wrap flex">
          <div class="lable">检查结果:</div>` +
        e +
        `</div>
        <div class="common-info-wrap flex">` +
        f +
        `</div>
      </div>
    </div>
      `

      // <div class="common-info-wrap flex">
      //   <div class="lable">检查详情:</div>

      let content = pre + a + mid + b + suf

      //初始化infoWindow
      this.infoWindow = new TMap.InfoWindow({
        map: this.map,
        enableCustom: true,
        position: new TMap.LatLng(34.348461, 108.94934),
        offset: { x: 0, y: -32 }, //设置信息窗相对position偏移像素
        content: content,
      })
      this.infoWindow.close() //初始关闭信息窗关闭

      window.close_x = () => {
        this.infoWindow.close() //初始关闭信息窗关闭
      }

      window.showImg = (id) => {
        this.werImg(id) //初始关闭信息窗关闭
      }

      window.jumpGoover = (checkTime) => {
        let queryParam = {
          policeAgencyId: checkTime.policeAgencyId,
          companyMessageId: checkTime.companyMessageId,
          companyMessageName: checkTime.companyMessageName,
        }
        this.$router.push({ path: '/goover/index', query: queryParam })
        // this.jumpGoover(id) //初始关闭信息窗关闭
      }

      window.jumpGooverDetail = (records) => {
        // console.log(records, 'companyMessageId, policeAgencyId')
        //checkType  1： 检查单  2：复查单
        //checkResult  1： 合格  2：不合格
        if (records.checkType == 1 && records.checkResult == 1) {
          this.$router.push({ path: '/goover/detailsGooverModal', query: { records } })
        } else {
          this.$router.push({ path: '/goover/noDetailsGooverModal', query: { records } })
        }
      }
    },

    werImg(id) {
      const ViewerDom = document.getElementById(id)
      const viewer = new Viewer(ViewerDom, {
        toolbar: true,
        button: false,
        navbar: false,
        title: false,
        url: 'data-original',
        hide: function () {
          viewer.destroy()
        },
      })
      viewer.show()
    },
  },
  destroyed() {},
}
</script>

<style scoped lang="less">
.map-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  // background: yellow;
}
</style>
